package com.zxl.working.service.impl;

import com.google.gson.Gson;
import com.zxl.working.entity.admin.SysUser;
import com.zxl.working.entity.backend.InvocerAlert;
import com.zxl.working.entity.backend.SellerBill;
import com.zxl.working.entity.backend.SellerInfo;
import com.zxl.working.entity.backend.SellerTax;
import com.zxl.working.entity.backend.ServiceInfo;
import com.zxl.working.entity.dto.ServiceInvoice;
import com.zxl.working.mapper.backend.ServiceMapper;
import com.zxl.working.service.ServiceService;
import com.zxl.working.utils.CommUtil;
import com.zxl.working.utils.HttpUtil;
import com.zxl.working.utils.SerialNoUtil;

import org.apache.http.client.utils.DateUtils;
import org.apache.ibatis.annotations.Case;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ServiceServiceImpl implements ServiceService {

    private Logger logger = LogManager.getLogger(ServiceServiceImpl.class);

    @Resource
    private ServiceMapper serviceMapper;
    @Resource
    private SerialNoUtil serialNoUtil;
    @Resource
    private Gson gson;
    @Resource
    private CommUtil commUtil;
    
    @Value("${request.url}")
    private String requestUrl;
    
    @Autowired
    private HttpUtil httpUtil;

    public String qryServiceInvoice(String serviceId,String params){
        Map<String,String> paramMap = gson.fromJson(params,Map.class);
        int page = Integer.parseInt(paramMap.getOrDefault("page", "1"));
        int pageSize = Integer.parseInt(paramMap.getOrDefault("pageSize", "10"));
        int start = (page - 1)* pageSize;
        Integer status = Integer.parseInt(paramMap.getOrDefault("status", "-1"));
        String sellerName = paramMap.getOrDefault("sellerName", "");
        List<ServiceInvoice> invoices = serviceMapper.qryServiceInvoice(serviceId,status,sellerName,start,pageSize);
        Integer cnt = serviceMapper.qryServiceInvoiceCnt(serviceId,status);

        Map<String,Object> resMap = new HashMap<>();
        resMap.put("list",invoices);
        resMap.put("total",cnt);

        return commUtil.returnSuccess(resMap);
    }

    public String updServiceInvoice(String serviceId,SellerBill sellerBill){
        serviceMapper.updBill(sellerBill);
        
        Integer totalAmount=serviceMapper.findByMoney(serviceId);
        
        Integer totalSum=serviceMapper.totalSum(serviceId);
        
        InvocerAlert invocerAlert= serviceMapper.findByInvice(serviceId);
        
        if(invocerAlert != null){
        if(totalAmount >= invocerAlert.getInvoiceMoney() && invocerAlert.getInvoiceMoney() != 0 && invocerAlert.getInvoiceMoney() != null){
        	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
        	/*TODO 增加邮件发送*/
            httpUtil.get(requestUrl+"/backend/dict/sendMain?flag=6&name="+ invocerAlert.getDatadicValue() + "&money=额度"+"&time="+ formatter.format(new java.util.Date()));
        }
        if(totalSum >= invocerAlert.getInvoiceSum() && invocerAlert.getInvoiceSum() != 0 && invocerAlert.getInvoiceSum() != null){
        	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
        	/*TODO 增加邮件发送*/
            httpUtil.get(requestUrl+"/backend/dict/sendMain?flag=6&name="+ invocerAlert.getDatadicValue() + "&money=张数"+"&time="+ formatter.format(new java.util.Date()));
        }
        }
        

        return commUtil.returnSuccess("");
    }
    
    
	@Override
	public String updexpress(SellerBill sellerBill) {
		serviceMapper.updexpress(sellerBill);
		 return commUtil.returnSuccess("");
	}
    

    public String billFail(String params){
        Map<String,String> paramMap = gson.fromJson(params,Map.class);

        String code = paramMap.get("billCode");

        serviceMapper.billFail(code);

        return commUtil.returnSuccess("");
    }

    public String qryTaxByServiceId(String serviceId,String params){
        Map<String,String> paramMap = gson.fromJson(params,Map.class);
        int page = Integer.parseInt(paramMap.getOrDefault("page", "1"));
        int pageSize = Integer.parseInt(paramMap.getOrDefault("pageSize", "10"));
        int start = (page - 1)* pageSize;
        List<SellerTax> taxes = serviceMapper.qryTaxsByServiceId(serviceId,start,pageSize);
        Integer cnt = serviceMapper.qryTaxsByServiceIdCnt(serviceId);

        Map<String,Object> resMap = new HashMap<>();
        resMap.put("list",taxes);
        resMap.put("total",cnt);

        return commUtil.returnSuccess(resMap);
    }

    public String insTax(SysUser sysUser, String serviceId, SellerTax tax){
        tax.setId(commUtil.getId());
        tax.setServiceId(serviceId);
        serviceMapper.insTax(tax);

        return commUtil.returnSuccess("");
    }

    public String qryAllService(String sellerId){
        List<ServiceInfo> serviceInfos = serviceMapper.qryAllServiceInfo(sellerId);

        return commUtil.returnSuccess(serviceInfos);
    }

    public String qrySellerInfoByService(String serviceId){
        List<SellerInfo> sellerInfos = serviceMapper.qrySellerInfoByService(serviceId);

        return commUtil.returnSuccess(sellerInfos);
    }

	@Override
	public String export(HttpServletResponse resp,String serviceId,Integer status) {
		List<ServiceInvoice> invoices = serviceMapper.export(serviceId,status);
		ServletOutputStream outputStream = null;
		export(outputStream,invoices,resp,status);
		return null;
	}
	
	private void export(ServletOutputStream outputStream,List<ServiceInvoice> all, HttpServletResponse resp,Integer status) {
		try {
			 //一.创建工作搏
            XSSFWorkbook workbook = new XSSFWorkbook();
            //二.创建工作表
            XSSFSheet sheet = workbook.createSheet("开票信息");
            //设置日期格式
            XSSFCellStyle style = workbook.createCellStyle();
            short fommart = workbook.createDataFormat().getFormat("yyyy年MM月dd日");
            style.setDataFormat(fommart);
            //三.创建行  ---下标为0
            XSSFRow sheetRow = sheet.createRow(0);
            //填充表头
            List<String> splitTitles = new ArrayList<>();
            splitTitles.add("发票编号");
            splitTitles.add("购买方名称");
            splitTitles.add("购买方纳税人识别号");
            splitTitles.add("购买方手机号");
            splitTitles.add("购买方地址");
            splitTitles.add("开户行");
            splitTitles.add("卡号");
            splitTitles.add("发票内容");
            splitTitles.add("发票金额");
            splitTitles.add("收票人姓名");
            splitTitles.add("收票人手机号");
            splitTitles.add("收票人地址");
            splitTitles.add("发票号");
            splitTitles.add("快递单号");
            splitTitles.add("销售方名称");
            splitTitles.add("销售方纳税人识别码");
            splitTitles.add("申请公司");
            splitTitles.add("申请时间");
            splitTitles.add("状态");
            // Set height of the row
            sheetRow.setHeight((short) 500);
            // Create a new font and alter it.
            XSSFFont font = workbook.createFont();
            //冻结第一行
            sheet.createFreezePane( 0, 1, 0, 1 );
            //处理标题行
            for (int i = 0; i < splitTitles.size(); i++) {
                XSSFCell cell = sheetRow.createCell(i);
                sheetRow.setHeight((short) 500);
                cell.setCellValue(splitTitles.get(i));
                cell.setCellStyle(style);
                if (i < 2) {
                    sheet.setColumnWidth(i, 7000);
                } else if (i == 2) {
                    sheet.setColumnWidth(i, 5000);
                } else {
                    sheet.setColumnWidth(i, 4000);
                }
            }
            
         // 处理数据行
            for(int i=1;i<=all.size();i++){
                sheetRow = sheet.createRow(i);
                if(all.get(i-1).getBillCode() != null){
                	 sheetRow.createCell(0).setCellValue(all.get(i-1).getBillCode());
                }//发票编号
                if(all.get(i-1).getSellerCompanyName() != null){
               	 sheetRow.createCell(1).setCellValue(all.get(i-1).getSellerCompanyName());
               }//购买方名称
                if(all.get(i-1).getTaxPayerCode() != null){
               	 sheetRow.createCell(2).setCellValue(all.get(i-1).getTaxPayerCode());
               }//购买方纳税人识别号
                if(all.get(i-1).getSellerMobile() != null){
                  	 sheetRow.createCell(3).setCellValue(all.get(i-1).getSellerMobile());
                  }//购买手机号
                if(all.get(i-1).getSellerAddress() != null){
                 	 sheetRow.createCell(4).setCellValue(all.get(i-1).getSellerAddress());
                 }//购买地址
                if(all.get(i-1).getSellerBank() != null){
                  	 sheetRow.createCell(5).setCellValue(all.get(i-1).getSellerBank());
                  }//开户行
                if(all.get(i-1).getSellerBankAccount() != null){
                 	 sheetRow.createCell(6).setCellValue(all.get(i-1).getSellerBankAccount());
                 }//账号
                if(all.get(i-1).getBillContent() != null){
               	 sheetRow.createCell(7).setCellValue(all.get(i-1).getBillContent());
               }//发票内容
                if(all.get(i-1).getTaxableTotal() != null){
               	 sheetRow.createCell(8).setCellValue(all.get(i-1).getTaxableTotal());
               }//发票金额
                if(all.get(i-1).getRname() != null){
                  	 sheetRow.createCell(9).setCellValue(all.get(i-1).getRname());
                  }//收票人姓名
                   if(all.get(i-1).getMobile() != null){
                  	 sheetRow.createCell(10).setCellValue(all.get(i-1).getMobile());
                  }//收票人手机号
                   if(all.get(i-1).getAddress() != null){
                  	 sheetRow.createCell(11).setCellValue(all.get(i-1).getAddress());
                  }//收票人地址
                if(all.get(i-1).getBillNumber() != null){
               	 sheetRow.createCell(12).setCellValue(all.get(i-1).getBillNumber());
               }//发票号
                if(all.get(i-1).getExpressCode() != null){
               	 sheetRow.createCell(13).setCellValue(all.get(i-1).getExpressCode());
               }//快递单号
                if(all.get(i-1).getServiceName() != null){
               	 sheetRow.createCell(14).setCellValue(all.get(i-1).getServiceName());
               }//销售方名称
                if(all.get(i-1).getEnterpriseCode() != null){
               	 sheetRow.createCell(15).setCellValue(all.get(i-1).getEnterpriseCode());
               }//销售方纳税人识别码
                if(all.get(i-1).getSellerName() != null){
               	 sheetRow.createCell(16).setCellValue(all.get(i-1).getSellerName());
               }//申请公司
                if(all.get(i-1).getCreateTime() != null){
               	 sheetRow.createCell(17).setCellValue(DateUtils.formatDate(all.get(i-1).getCreateTime(),"yyyy-MM-dd"));
               }//申请时间
                if(all.get(i-1).getStatus() != null){
                  	 sheetRow.createCell(18).setCellValue(getStatus(all.get(i-1).getStatus()));
                  }//状态
            }
            
            String format = new SimpleDateFormat("MM-dd").format(new Date());
         // 响应设置
            // 响应头 编码格式ISO8859-1
            resp.setHeader("content-disposition", "attachment;filename="
                    + URLEncoder.encode("开票信息", "utf-8") + "-" + format
                    + ".xlsx");
            // 响应内容
            resp.setContentType("application/vnd.ms-excel");

            // 将workbook输出流的方式下载到客户端
            outputStream = resp.getOutputStream();
            workbook.write(outputStream);

		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public String getStatus(Integer status){
		String sum="未知";
		switch(status){
		case 0:
			sum="未开票";
			break;
		case 1:
			sum ="已开票";
			break;
		}
		return sum;
		
	}

	@Override
	@Transactional
	public String updateInvoice(String serviceId,Integer invoiceMoney, String invoiceMail,Integer invoiceSum) {
		InvocerAlert invocerAlert= serviceMapper.findByInvice(serviceId);
		if(invocerAlert == null){
			serviceMapper.insertInvoice(serviceId,invoiceMoney,invoiceMail,invoiceSum);
		}else{
			serviceMapper.updateInvoice(serviceId,invoiceMoney,invoiceMail,invoiceSum);
		}
		
		return commUtil.returnStr(0, "设置成功", "");
	}

	@Override
	public String findByInvocer(String serviceId) {
		InvocerAlert invocerAlert= serviceMapper.findByInvice(serviceId);
		return commUtil.returnStr(0, "查询成功", invocerAlert);
	}




}
